var express = require('express'),
    router = require('./router'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    app = express(),
    sd = require('silly-datetime');
Chat = require('./model/chat')


var http = require('http').Server(app);
var io = require('socket.io')(http);

// 当前在线人数
let count = 0;
// 总访客人数
let totalCount = 0;


app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 1000 * 60
    },
}));

app.use(bodyParser.urlencoded({
    extended: false
}))
app.use(bodyParser.json())

app.use(router)

io.on("connection", (socket) => {
    count++;
    totalCount++;
    let name = '';
    // 加入群聊
    socket.on("join", function (message) {
        console.log(message);
        name = message.name;
        console.log(name + "加入了群聊");
        // 给公众发消息
        socket.broadcast.emit("joinNoticeOther", {
            name: name,
            action: "加入了群聊",
            count: count
        });
        // 给自己发消息
        socket.emit("joinNoticeSelf", {
            count: count
        });
    });

    // 接收客户端所发送的信息
    socket.on("message", function (message) {
        
        console.log(message);
        message.time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss')
        Chat.SaveChat(message, (err, data) => {
            // 向所有客户端广播发布的消息
            if (err) { throw err }
            io.emit("message", message);
        })
    });

    //	 监听到连接断开
    socket.on("disconnect", function () {
        count--;
        console.log(name + "离开了群聊")
        io.emit("disconnection", {
            count: count,
            name: name,
            action: "离开了群聊",
        });
    });
});

http.listen(3000, function (err) {
    if (err) {
        throw errr
    }
    console.log("server start , running in 3000")
});